import 'dart:developer';
import 'package:amap_map_fluttify/amap_map_fluttify.dart';
import 'package:permission_handler/permission_handler.dart'
    as permission_handler;
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter/services.dart';
import '../../index.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart'
    as extended;

class WorkOrderDetailsPage extends StatefulWidget {
  late String orderId;
  late String? taskId;

  WorkOrderDetailsPage({Key? key, required this.orderId, this.taskId})
      : super(key: key);

  @override
  _WorkOrderDetailsState createState() => _WorkOrderDetailsState();
}

class _WorkOrderDetailsState extends State<WorkOrderDetailsPage>
    with SingleTickerProviderStateMixin {
  final PageData<Order> _pageData = PageData<Order>();
  final PageData<TaskLog> _pageLogData = PageData<TaskLog>();
  AmapController? _mapController;
  final List<String> _tabs = <String>['报修详情', '处理内容', '操作内容'];

  @override
  Widget build(BuildContext context) {
    if (_pageData.item == null && _pageData.loadStatus == LoadStatus.loadNot) {
      _handlerLoadData();
    }
    // TODO: implement build
    return GlobalStyle(
      child: BackgroundStyleWidget(
        child: _pageData.item != null
            ? DefaultTabController(
                length: _tabs.length, // This is the number of tabs.
                child: Scaffold(
                  appBar: AppBar(
                    title: Text(widget.taskId == null ? "工单详情" : "待办详情"),
                    centerTitle: true,
                    actions: <Widget>[
                      TextButton(
                          child: Row(
                            children: [
                              Text("导航"),
                              Image(
                                  image: AssetImage(
                                      "images/common_navigation.png")),
                            ],
                          ),
                          onPressed: () async {
                            LatLng coordinate = LatLng(
                                double.parse(_pageData.item!.latitude ?? ""),
                                double.parse(_pageData.item!.longitude ?? ""));
                            Debug.info("${coordinate.latitude}-----${coordinate.longitude}");
                            try {
                              await AmapService.instance.navigateDrive(
                                  coordinate,
                                  // appName: "",
                                  dev: 0);
                            } catch (e) {
                              showToast(e.toString());
                            }
                            //
                          }),
                    ],
                  ),
                  body: _buildBody(), // 构建主页面
                ))
            : Scaffold(
                appBar: AppBar(
                  title: Text(widget.taskId == null ? "工单详情" : "待办详情"),
                  centerTitle: true,
                ),
                body: HintWidget(pageData: _pageData),
              ),
      ),
    );
  }

  Future<void> _onMapCreated(AmapController controller) async {
    _mapController = controller;
    if (await permission_handler.Permission.location
        .request()
        .then((it) => it.isGranted)) {
      await controller.showMyLocation(MyLocationOption(
        show: true,
        // 是否显示
        myLocationType: MyLocationType.Show,
      ));
      LatLng coordinate = LatLng(double.parse(_pageData.item!.latitude ?? ""),
          double.parse(_pageData.item!.longitude ?? ""));
      //移动到中心点
      controller.setCenterCoordinate(LatLng(
          double.parse(_pageData.item!.latitude ?? ""),
          double.parse(_pageData.item!.longitude ?? "")));
      //添加标注
      controller.addMarker(MarkerOption(
          title: "故障地点", coordinate: coordinate, anchorU: 0.5, anchorV: 0.5));
    } else {
      showToast('权限请求被拒绝!');
    }
  }

  // 初始化
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  Widget _buildBody() {
    Widget divider = Divider(
      color: Theme.of(context).colorScheme.surface,
    );
    List<Widget> list = <Widget>[];

    var darkModel = Provider.of<DarkModel>(context);
    if (_mapController != null) {
      _mapController?.setMapType(
          darkModel.isDark(context) ? MapType.Night : MapType.Standard);
    }

    list.add(
      Expanded(
        child: extended.ExtendedNestedScrollView(
            headerSliverBuilder:
                (BuildContext context, bool innerBoxIsScrolled) {
              return <Widget>[
                SliverToBoxAdapter(
                  child: SizedBox(
                    height: 250,
                    child: AmapView(
                      zoomLevel: 15,
                      mapType: darkModel.isDark(context)
                          ? MapType.Night
                          : MapType.Standard,
                      onMapCreated: _onMapCreated,
                    ),
                  ),
                )
              ];
            },
            body: Column(
              children: [
                PreferredSize(
                    child: TabBar(
                      tabs:
                          _tabs.map((String name) => Tab(text: name)).toList(),
                      labelColor: Theme.of(context).primaryColor,
                      unselectedLabelColor:
                          Theme.of(context).colorScheme.onPrimary,
                      indicatorColor: Theme.of(context).primaryColor,
                      indicatorSize: TabBarIndicatorSize.label,
                    ),
                    preferredSize: const Size(double.infinity, 46.0)),
                Container(
                  height: 5,
                  color: Theme.of(context).colorScheme.surface,
                ),
                Expanded(
                  child: TabBarView(
                    children: _tabs.map((String name) {
                      return Builder(
                        builder: (BuildContext context) {
                          return _buildTabView(context, name);
                        },
                      );
                    }).toList(),
                  ),
                ),
              ],
            )),
      ),
    );

    List<ExecuteTaskOperation> operations = [];
    if (_pageData.item!.orderStatus == 0 && executeTask == null) {
      if (PermissionCache().getPermission("work_order_send") != null) {
        operations.add(ExecuteTaskOperation()
          ..label = "发送"
          ..identType = "order_send");
      }
      //待分配并有编辑权限时 添加编辑按钮
      if (PermissionCache().getPermission("work_order_edit") != null) {
        // &&
        // _pageData.item?.createUser == Global.profile.user?.userId) {
        operations.add(ExecuteTaskOperation()
          ..label = "编辑"
          ..identType = "order_update");
      }
      if (PermissionCache().getPermission("work_order_delete") != null) {
        operations.add(ExecuteTaskOperation()
          ..label = "删除"
          ..identType = "order_delete");
      }
    } else {
      //待发送
      if (executeTask?.operationList != null) {
        operations = executeTask!.operationList!;
      }
    }

    if (operations.isNotEmpty) {
      List<Widget> btns = [];
      if (operations.length == 2) {
        //显示操作按钮
        var operation = operations[1];
        btns.add(Expanded(
          child: ConstrainedBox(
            constraints: const BoxConstraints.expand(height: 45.0),
            child: ElevatedButton(
              style: ButtonStyle(
                //背景颜色
                backgroundColor: MaterialStateProperty.resolveWith(
                  (states) {
                    return Theme.of(context).colorScheme.secondary;
                  },
                ),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(0))),
              ),
              onPressed: () => {_handleOrder(operation.identType!)},
              child: Text(
                "${operation.label}",
                style: Theme.of(context)
                    .textTheme
                    .titleMedium
                    ?.copyWith(color: Theme.of(context).colorScheme.background),
              ),
            ),
          ),
        ));
      } else if (operations.length > 2) {
        List<Widget> otherBtns = [];
        for (int i = 1; i < operations.length; i++) {
          var operation = operations[i];
          otherBtns.add(
            ListTile(
                title: Center(
                  child: Text("${operation.label}"),
                ),
                onTap: () {
                  Navigator.pop(context);
                  //处理工单
                  _handleOrder(operation.identType!);
                }),
          );
          if (i != operations.length - 1) {
            otherBtns.add(divider);
          }
        }
        //显示其他按钮
        btns.add(Expanded(
          child: ConstrainedBox(
            constraints: const BoxConstraints.expand(height: 45.0),
            child: ElevatedButton(
              style: ButtonStyle(
                //背景颜色
                backgroundColor: MaterialStateProperty.resolveWith(
                  (states) {
                    return Theme.of(context).colorScheme.secondary;
                  },
                ),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(0))),
              ),
              onPressed: () {
                //选择照片
                showModalBottomSheet(
                  context: context,
                  builder: (BuildContext context) {
                    return SafeArea(
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: otherBtns,
                      ),
                    );
                  },
                );
              },
              child: Text(
                "其他操作",
                style: Theme.of(context)
                    .textTheme
                    .titleMedium
                    ?.copyWith(color: Theme.of(context).colorScheme.background),
              ),
            ),
          ),
        ));
      }

      var mainOperation = operations[0];
      btns.add(
        Expanded(
          child: ConstrainedBox(
            constraints: const BoxConstraints.expand(height: 45.0),
            child: ElevatedButton(
              style: ButtonStyle(
                //背景颜色
                backgroundColor: MaterialStateProperty.resolveWith(
                  (states) {
                    return Theme.of(context).primaryColor;
                  },
                ),
                shape: MaterialStateProperty.all(RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(0))),
              ),
              onPressed: () => {_handleOrder(mainOperation.identType!)},
              child: Text(
                "${mainOperation.label}",
                style: Theme.of(context)
                    .textTheme
                    .titleMedium
                    ?.copyWith(color: Theme.of(context).colorScheme.background),
              ),
            ),
          ),
        ),
      );

      list.add(Row(
        children: btns,
      ));
    }

    return SafeArea(child: Column(children: list));
  }

  String? selectName;

  void _handleOrder(String identType) async {
    Debug.info("---$identType--");
    switch (identType) {
      case "order_update":
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => WorkOrderAddPage(
                  order: _pageData.item,
                )));
        break;
      case "order_delete":
        showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                title: const Text('确认提示'),
                content: const Text('确认是否删除工单?'),
                actions: <Widget>[
                  TextButton(
                    child: const Text('取消'),
                    onPressed: () {
                      Navigator.of(context).pop('cancel');
                    },
                  ),
                  TextButton(
                    child: const Text('确认'),
                    onPressed: () {
                      Navigator.of(context).pop();
                      _deleteOrder();
                    },
                  ),
                ],
              );
            });
        break;
      case "order_send":
        showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                title: const Text('确认提示'),
                content: const Text('确认是否发送工单?'),
                actions: <Widget>[
                  TextButton(
                    child: const Text('取消'),
                    onPressed: () {
                      Navigator.of(context).pop('cancel');
                    },
                  ),
                  TextButton(
                    child: const Text('确认'),
                    onPressed: () {
                      Navigator.of(context).pop();
                      _sendOrder();
                    },
                  ),
                ],
              );
            });
        break;
      case "order_back":
        TextEditingController _textEditingController = TextEditingController();
        showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                title: const Text('确认提示'),
                content: TextField(
                  controller: _textEditingController,
                  keyboardType: TextInputType.multiline,
                  maxLength: 100,
                  textInputAction: TextInputAction.done,
                  maxLines: 5,
                  decoration: const InputDecoration(
                      // labelText: content,
                      border: OutlineInputBorder(),
                      hintText: "请输入工单回退原因"),
                ),
                actions: <Widget>[
                  TextButton(
                    child: const Text('取消'),
                    onPressed: () {
                      Navigator.of(context).pop('cancel');
                    },
                  ),
                  TextButton(
                    child: const Text('确认'),
                    onPressed: () {
                      if (_textEditingController.text.isEmpty) {
                        //不能为空
                        showToast("回退原因不能为空");
                      } else {
                        Navigator.of(context).pop();
                        _backOrder(_textEditingController.text);
                      }
                    },
                  ),
                ],
              );
            });
        break;
      case "order_confirm":
        // 跳转到用户选择界面

        List result = await Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => SelectUserPage(
                  selectUserType: SelectUserType.dept,
                  title: "请选择负责人",
                )));
        if (result.isNotEmpty) {
          UserInfo userInfo = result[0];

          showDialog(
              context: context,
              builder: (context) {
                return AlertDialog(
                  title: const Text('确认提示'),
                  content: Text('确认是否分配工单给${userInfo.name}？'),
                  actions: <Widget>[
                    TextButton(
                      child: const Text('取消'),
                      onPressed: () {
                        Navigator.of(context).pop('cancel');
                      },
                    ),
                    TextButton(
                      child: const Text('确认'),
                      onPressed: () {
                        Navigator.of(context).pop();

                        TaskRequest taskRequest = TaskRequest();
                        taskRequest.businessFrom = {
                          "handleUserId": userInfo.id
                        };
                        taskRequest.values = {"appointedAssignee": userInfo.id};
                        taskRequest.operationType = "agree";
                        taskRequest.taskId = executeTask?.taskId;
                        _handelOrder(taskRequest);
                      },
                    ),
                  ],
                );
              });
        }

        break;
      case "order_handle":
        Navigator.of(context).push(MaterialPageRoute(
            builder: (context) => WorkOrderHandlePage(
                  orderId: widget.orderId,
                  taskId: executeTask!.taskId!,
                )));
        break;
      case "order_over":
        showDialog(
            context: context,
            builder: (context) {
              return AlertDialog(
                title: const Text('确认提示'),
                content: const Text('是否终结工单，确认工单已处理完成？'),
                actions: <Widget>[
                  TextButton(
                    child: const Text('取消'),
                    onPressed: () {
                      Navigator.of(context).pop('cancel');
                    },
                  ),
                  TextButton(
                    child: const Text('确认'),
                    onPressed: () {
                      Navigator.of(context).pop();
                      TaskRequest taskRequest = TaskRequest();
                      taskRequest.operationType = "agree";
                      taskRequest.taskId = executeTask?.taskId;
                      _handelOrder(taskRequest);
                    },
                  ),
                ],
              );
            });
        break;
      case "order_plfile":
        showDialog(
            context: context,
            builder: (context) {
              return WorkOrderPlfilePage(
                orderId: widget.orderId,
                taskId: executeTask!.taskId!,
              );
            });
        break;
      default:
        break;
    }
  }

  void _handelOrder(TaskRequest taskRequest) async {
    showLoading(context);
    try {
      ResponseData responseData =
          await Api(context).handleOrder(taskRequest: taskRequest);
      Navigator.of(context).pop();
      if (responseData.success) {
        eventBus.fire(OrderEvent(EventType.edit, _pageData.item!));
        await showToast(responseData.msg);
        Navigator.of(context).pushReplacement(MaterialPageRoute(
            settings: const RouteSettings(name: "WorkOrderDetails"),
            builder: (context) =>
                WorkOrderDetailsPage(orderId: _pageData.item!.id!)));
      } else {
        showToast(responseData.msg);
      }
    } on DioError catch (e) {
      Navigator.of(context).pop();
      //失败则提示
      showToast(e.response?.statusMessage ?? S.of(context).networkError);
    } on Error catch (e) {
      Navigator.of(context).pop();
      showToast(Global.isRelease ? S.of(context).networkError : e.toString());
    }
  }

  void _backOrder(String backReason) async {
    showLoading(context);
    try {
      TaskRequest taskRequest = TaskRequest();
      taskRequest.message = backReason;
      taskRequest.operationType = "reject";
      taskRequest.taskId = executeTask?.taskId;
      ResponseData responseData =
          await Api(context).backOrder(taskRequest: taskRequest);
      Navigator.of(context).pop();
      if (responseData.success) {
        eventBus.fire(OrderEvent(EventType.edit, _pageData.item!));
        await showToast(responseData.msg);
        Navigator.of(context).pushReplacement(MaterialPageRoute(
            settings: const RouteSettings(name: "WorkOrderDetails"),
            builder: (context) =>
                WorkOrderDetailsPage(orderId: _pageData.item!.id!)));
      } else {
        showToast(responseData.msg);
      }
    } on DioError catch (e) {
      Navigator.of(context).pop();
      //失败则提示
      showToast(e.response?.statusMessage ?? S.of(context).networkError);
    } on Error catch (e) {
      Navigator.of(context).pop();
      showToast(Global.isRelease ? S.of(context).networkError : e.toString());
    }
  }

  void _deleteOrder() async {
    showLoading(context, text: "正在删除");
    try {
      ResponseData responseData =
          await Api(context).deleteOrder(ids: _pageData.item!.id!);
      Navigator.of(context).pop();
      if (responseData.success) {
        //删除成功
        eventBus.fire(OrderEvent(EventType.delete, _pageData.item!));
        await showToast(responseData.msg);
        Navigator.of(context).pop();
      } else {
        //请求失败
        showToast(responseData.msg);
      }
    } on DioError catch (e) {
      Navigator.of(context).pop();
      //失败则提示
      showToast(e.response?.statusMessage ?? S.of(context).networkError);
    } on Error catch (e) {
      Navigator.of(context).pop();
      showToast(Global.isRelease ? S.of(context).networkError : e.toString());
    }
  }

  void _sendOrder() async {
    showLoading(context, text: "正在发送");
    try {
      ResponseData responseData =
          await Api(context).sendOrder(orderId: _pageData.item!.id!);
      Navigator.of(context).pop();
      if (responseData.success) {
        //成功
        eventBus.fire(OrderEvent(EventType.edit, _pageData.item!));
        await showToast(responseData.msg);
        Navigator.of(context).pushReplacement(MaterialPageRoute(
            settings: const RouteSettings(name: "WorkOrderDetails"),
            builder: (context) =>
                WorkOrderDetailsPage(orderId: _pageData.item!.id!)));
      } else {
        //请求失败
        showToast(responseData.msg);
      }
    } on DioError catch (e) {
      Navigator.of(context).pop();
      //失败则提示
      showToast(e.response?.statusMessage ?? S.of(context).networkError);
    } on Error catch (e) {
      Navigator.of(context).pop();
      showToast(Global.isRelease ? S.of(context).networkError : e.toString());
    }
  }

  Widget _buildTabView(BuildContext context, String name) {
    switch (_tabs.indexOf(name)) {
      case 0:
        {
          //报修详情
          return _drawRepairDetails(context, name);
        }
      case 1:
        {
          //处理内容
          return _drawProcessContent(context, name);
        }

      default:
        //操作内容
        return _drawOperationContent(context, name);
    }
  }

  Future _handlerLoadData() async {
    try {
      _pageData.loadStatus = LoadStatus.loading;
      ResponseData<Order> responseData =
          await Api(context).getOrder(queryParameters: {'id': widget.orderId});
      if (responseData.success) {
        if (mounted) {
          setState(() {
            _pageData.loadStatus = LoadStatus.loadSuccess;
            _pageData.item = responseData.dataModel;
          });
        }
        _handlerLoadExecuteTaskData();
        _handlerOperationRefresh();
      } else {
        _pageData.hint = responseData.msg;
        //请求失败
        showToast(responseData.msg);
        setState(() {
          _pageData.loadStatus = LoadStatus.loadFail;
        });
      }
    } on DioError catch (e) {
      //登录失败则提示
      _pageData.hint = e.response?.statusMessage ?? S.of(context).networkError;
      _pageData.code = e.response?.statusCode;
      _pageData.errorType = e.type;
      showToast(e.response?.statusMessage ?? S.of(context).networkError);
      setState(() {
        _pageData.loadStatus = LoadStatus.loadFail;
      });
    } on Error catch (e) {
      Debug.info("错误：" + e.toString());
      Debug.info(e.stackTrace.toString());
      //登录失败则提示
      _pageData.hint =
          Global.isRelease ? S.of(context).networkError : e.toString();
      showToast(Global.isRelease ? S.of(context).networkError : e.toString());
      setState(() {
        _pageData.loadStatus = LoadStatus.loadFail;
      });
    } finally {}
  }

  ExecuteTask? executeTask;

  Future _handlerLoadExecuteTaskData() async {
    try {
      ResponseData<ExecuteTask> responseData = await Api(context)
          .getExecuteTaskData(businessKey: _pageData.item!.id);
      if (responseData.success) {
        if (responseData.dataModel?.taskId != null && mounted) {
          setState(() {
            executeTask = responseData.dataModel;
          });
        }
      } else {
        //请求失败
        showToast(responseData.msg);
      }
    } on DioError catch (e) {
      //失败则提示
      showToast(e.response?.statusMessage ?? S.of(context).networkError);
    } on Error catch (e) {
      showToast(Global.isRelease ? S.of(context).networkError : e.toString());
    }
  }

  // Widget padding = Padding(padding: const EdgeInsets.all(5));
  Widget _drawRepairDetails(BuildContext context, String name) {
    Widget container = Container(
      height: 10,
      color: Theme.of(context).colorScheme.surface,
    );
    return CustomScrollView(
        key: PageStorageKey<String>(name),
        slivers: <Widget>[
          // SliverOverlapInjector(
          //   handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
          // ),
          SliverList(
            delegate: SliverChildListDelegate(
              [
                CommonText(
                    title: "报修内容", content: _pageData.item!.suppleMemo ?? ""),
                CommonText(
                  title: "故障地点",
                  content: _pageData.item!.defectAddress ?? "",
                ),
                CommonText(
                  title: "详细地址",
                  content: _pageData.item!.address ?? "",
                ),
                CommonText(
                  title: "工单编号",
                  content: _pageData.item!.orderCode ?? "",
                  style: const TextStyle(color: Colors.blue),
                  isHideDivide: true,
                  onTap: () {
                    if (_pageData.item!.orderCode != null) {
                      //复制
                      Clipboard.setData(
                          ClipboardData(text: _pageData.item!.orderCode ?? ""));
                      showToast("复制成功");

                      // showModalBottomSheet(
                      //   context: context,
                      //   builder: (BuildContext context) {
                      //     return SafeArea(
                      //       child: Column(
                      //         mainAxisSize: MainAxisSize.min,
                      //         children: <Widget>[
                      //           ListTile(
                      //             leading: Icon(Icons.copy),
                      //             title: Text("复制"),
                      //             onTap: () {
                      //               Navigator.pop(context);
                      //               Clipboard.setData(ClipboardData(text: "2333"));
                      //               showToast("复制成功");
                      //             },
                      //           ),
                      //         ],
                      //       ),
                      //     );
                      //   },
                      // );
                    }
                  },
                ),
                container,
                // ListTile(
                //   leading: const Text("详细地点"),
                //   title: Text(_pageData.item!.address),
                // ));
                CommonText(
                  title: "报修来源",
                  content: _pageData.item!.repairResourceName ?? "",
                ),
                CommonText(
                  title: "计划完单时间",
                  content: _pageData.item!.planCompleteTime ?? "",
                ),
                CommonText(
                  title: "出单时间",
                  content: _pageData.item!.createTime ?? "",
                ),
                CommonText(
                  title: "工单紧急程度",
                  content: _pageData.item!.orderUrgencyName ?? "",
                ),
                CommonText(
                  title: "客户姓名",
                  content: _pageData.item!.customerName ?? "",
                ),
                CommonText(
                  title: "联系方式",
                  content: _pageData.item!.customerPhone ?? "",
                  style: TextStyle(color: Colors.blue),
                  onTap: () {
                    if (_pageData.item!.customerPhone != null) {
                      launch("tel://${_pageData.item!.customerPhone}");
                    }
                  },
                ),
                CommonText(
                  title: "指派处理部门",
                  content:
                      DeptCache().getDeptName(_pageData.item!.handleDeptId),
                ),
                CommonPhotoWidget(
                    photoStr: _pageData.item!.annexUrl ?? "", title: "附图"),
                CommonText(
                  title: "备注",
                  content: _pageData.item!.orderMemo ?? "",
                  isHideDivide: true,
                ),
              ],
            ),
          ),
        ]);
  }

  late bool showOrderHandle = true;

  // GlobalKey<SliverAnimatedListState> _listKey =
  //     GlobalKey<SliverAnimatedListState>();

  Widget _drawProcessContent(BuildContext context, String name) {
    List<Widget> orderHandleList = [];

    // Widget _buildItem(int _index, Animation _animation) {
    //   // if (_index == 0) {
    //   //   return orderHandleList[_index];
    //   // }
    //   return SlideTransition(
    //       position: _animation
    //           .drive(CurveTween(curve: Curves.easeIn))
    //           .drive(Tween<Offset>(
    //               begin: Offset(0, -1.0 * (_index + 1) / 2),
    //               end: const Offset(0, 0))),
    //       child: orderHandleList[_index]);
    // }
    orderHandleList.add(Material(
      elevation: 10.0,
      child: ListTile(
        title: Text("工单处理"),
        trailing: Icon(showOrderHandle
            ? Icons.keyboard_arrow_down
            : Icons.keyboard_arrow_up),
        onTap: () {
          setState(() {
            showOrderHandle = !showOrderHandle;
          });
          // showOrderHandle = !showOrderHandle;
          // for (int i = 1; i < orderHandleList.length; i++) {
          //   if (showOrderHandle) {
          //     //正向添加
          //     _listKey.currentState
          //         ?.insertItem(i, duration: const Duration(milliseconds: 300));
          //   } else {
          //     //逆向删除
          //     _listKey.currentState?.removeItem(
          //         orderHandleList.length - i,
          //         (context, animation) =>
          //             _buildItem(orderHandleList.length - i, animation),
          //         duration: const Duration(milliseconds: 300));
          //   }
          // }
        },
      ),
    ));

    if (showOrderHandle) {
      orderHandleList.add(CommonText(
        title: "故障原因",
        content: _pageData.item!.faultReasonName ?? "",
      ));
      orderHandleList.add(CommonText(
        title: "处理内容",
        content: _pageData.item!.handleContent ?? "",
      ));
      if ((_pageData.item!.handleBeforImage ?? "").isNotEmpty) {
        orderHandleList.add(CommonPhotoWidget(
            photoStr: _pageData.item!.handleBeforImage!,
            title: "处理前图片",
            isHideDivide: true));
      }
      if ((_pageData.item!.handleAfterImage ?? "").isNotEmpty) {
        orderHandleList.add(CommonPhotoWidget(
            photoStr: _pageData.item!.handleAfterImage!,
            title: "处理后图片",
            isHideDivide: true));
      }
    }

    return CustomScrollView(
        key: PageStorageKey<String>(name),
        slivers: <Widget>[
          // SliverOverlapInjector(
          //   handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
          // ),
          SliverList(
            delegate: SliverChildListDelegate(orderHandleList),
          ),
          // SliverAnimatedList(
          //   initialItemCount: orderHandleList.length,
          //   key: _listKey,
          //   itemBuilder:
          //       (BuildContext context, int index, Animation<double> animation) {
          //     return _buildItem(index, animation);
          //   },
          //   // delegate: SliverChildListDelegate(orderHandleList),
          // ),
        ]);
  }

  final EasyRefreshController _controller = EasyRefreshController();

  Widget _drawOperationContent(BuildContext context, String name) {
    // return _pageLogData.items.isNotEmpty
    //     ? EasyRefresh(
    //     controller: _controller,
    //     onRefresh: () => _handlerOperationRefresh(),
    //     child: CustomScrollView(
    //       key: PageStorageKey<String>(name),
    //       slivers: <Widget>[
    //         SliverOverlapInjector(
    //           handle:
    //           NestedScrollView.sliverOverlapAbsorberHandleFor(context),
    //         ),
    //         SliverToBoxAdapter(
    //           child: container,
    //         ),
    //         SliverList(
    //           delegate: SliverChildBuilderDelegate(
    //                 (context, index) {
    //               return TaskLogItem(
    //                 taskLog: _pageLogData.items[index],
    //               );
    //             },
    //             childCount: _pageLogData.items.length,
    //           ),
    //         ),
    //       ],
    //     ))
    //     : HintWidget(pageData: _pageLogData);

    return EasyRefresh.custom(
      header: LightHeader(),
      footer: LightFooter(),
      emptyWidget: _pageLogData.items.isEmpty
          ? HintWidget(pageData: _pageLogData)
          : null,
      listKey: PageStorageKey<String>(name),
      controller: _controller,
      onRefresh: () => _handlerOperationRefresh(),
      slivers: [
        // SliverOverlapInjector(
        //   handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
        // ),
        SliverList(
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              return TaskLogItem(
                taskLog: _pageLogData.items[index],
                itemLocation:
                    ItemUtils.convertLocation(index, _pageLogData.items.length),
              );
            },
            childCount: _pageLogData.items.length,
          ),
        ),
      ],
    );
  }

  Future _handlerOperationRefresh() async {
    try {
      _pageLogData.loadStatus = LoadStatus.loading;
      ResponseData<List<TaskLog>> responseData =
          await Api(context).getTaskLogList(businessKey: widget.orderId);
      if (responseData.success) {
        List<TaskLog> orders = responseData.dataModel!;
        //如果返回的数据小于指定的条数，则表示没有更多数据，反之则否
        //把请求到的新数据添加到items中
        if (mounted) {
          setState(() {
            _pageLogData.loadStatus = LoadStatus.loadSuccess;
            _pageLogData.items = orders;
          });
        }
      } else {
        _pageLogData.hint = responseData.msg;
        //请求失败
        showToast(responseData.msg);
        setState(() {
          _pageData.loadStatus = LoadStatus.loadFail;
        });
      }
    } on DioError catch (e) {
      //登录失败则提示
      _pageLogData.hint =
          e.response?.statusMessage ?? S.of(context).networkError;
      _pageLogData.code = e.response?.statusCode;
      _pageLogData.errorType = e.type;
      if (_pageLogData.items.isNotEmpty) {
        showToast(e.response?.statusMessage ?? S.of(context).networkError);
      }
      setState(() {
        _pageData.loadStatus = LoadStatus.loadFail;
      });
    } on Error catch (e) {
      _pageLogData.hint =
          Global.isRelease ? S.of(context).networkError : e.toString();
      if (_pageLogData.items.isNotEmpty) {
        showToast(Global.isRelease ? S.of(context).networkError : e.toString());
      }
      setState(() {
        _pageData.loadStatus = LoadStatus.loadFail;
      });
    } finally {}
  }
}
